<script>
  import StyleSelect from './StyleSelect.vue';
  import { nanoid } from '@/utils';
  export default {
    name: 'VSelector',
    components: {
      StyleSelect,
    },
    inheritAttrs: false,
    props: {
      modelValue: {
        type: [Number, String, Array, Object], // 如果绑定值为数组，则为多选,否则为单选
        default: '',
      },
      isObjectValue: {
        // select框绑定的值是对象 还是值
        type: Boolean,
        default: false,
      },
      opsData: {
        type: Array,
        default: () => [],
      },
    },
    emits: ['update:modelValue'],
    data() {
      return {
        renderId: nanoid(8),
        CommonSelect: this.$root.$refs.CommonSelect,
      };
    },
    computed: {
      labelKey() {
        return this.$attrs['label-key'] || 'label';
      },
      valueKey() {
        return this.$attrs['value-key'] || 'id';
      },
      selectedData() {
        if (this.$attrs.multiple) {
          return this.modelValue.map((item) => {
            return this.opsData.find((i) => i[this.valueKey] === this.getOpsKey(item));
          });
        } else {
          return this.opsData.find((i) => i[this.valueKey] === this.getOpsKey(this.modelValue));
        }
      },
    },
    methods: {
      toggleMenu() {
        this.CommonSelect.toggleMenu({
          renderId: this.renderId,
          curInstance: this,
          attrs: this.$attrs,

          curValue: this.modelValue,
          isObjectValue: this.isObjectValue,
          opsData: this.opsData,
        });
      },
      // 不要删除，给CommonSelect调用
      updateValue(val) {
        this.$emit('update:modelValue', val);
      },
      deleteItem(item) {
        const idx = this.modelValue.findIndex((i) => i.id === item.id);
        // eslint-disable-next-line vue/no-mutating-props
        this.modelValue.splice(idx, 1);
      },
      getOpsKey(item) {
        if (this.isObjectValue) return item[this.valueKey];
        else return item;
      },
    },
  };
</script>

<template>
  <div class="virtual-select" @click.stop="">
    <StyleSelect
      v-bind="$attrs"
      :selected-data="selectedData"
      :is-object-value="isObjectValue"
      @toggleMenu="toggleMenu"
      @deleteItem="deleteItem"
    />
    <div :id="renderId" class="common-select" />
  </div>
</template>

<style lang="scss" scoped>
  .virtual-select {
    position: relative;
    .common-select {
      :deep(.el-select) {
        position: absolute;
        left: 0;
        top: 0;
        z-index: -1;
        :deep(.el-input) {
          opacity: 1;
        }
      }
    }
  }
</style>
